﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using mvcDemo.Models;
using System.Data;

namespace mvcDemo.Controllers
{
    public class PicTypeRemarkGroupsController : ApiController
    {
        public class PicTypeRemarkGroup
        {
            public string userId { get; set; }
            public string typeName { get; set; }
            public string remark { get; set; }
            public PicGroup[] picGroup { get; set; }

        }

        public class PicGroup
        {
            public string groupName { get; set; }
            public Pic[] pic { get; set; }
        }

        public class Pic
        {
            public string picTypeRemarkGroupId { get; set; }
            public string id { get; set; }
            public string fileName { get; set; }
            public bool del { get; set; }
        }

        // GET api/pictyperemarkgroups
        public JsonMessage Get()
        {
            //根据证件类型ID和评语ID获取
            try
            {
                int remarkId = int.Parse(HttpContext.Current.Request.QueryString["remarkid"]);
                int typeId = int.Parse(HttpContext.Current.Request.QueryString["typeid"]);
                using (Entities db = new Entities())
                {
                    List<PICTYPEREMARKGROUP> picTypeRemarkGroups = db.PICTYPEREMARKGROUP.Include("PIC").Include("REMARKGROUP")
                        .Where(a => a.TYPEID == typeId && a.REMARKID == remarkId)
                        .ToList();
                    return new JsonMessage(picTypeRemarkGroups);
                }
            }
            catch (Exception ex)
            {
                return new JsonMessage("获取资源失败！", ex.Message, ex.StackTrace);
            }
        }

        // POST api/pictyperemarkgroups
        public JsonMessage Post([FromBody]PicTypeRemarkGroup obj)
        {
            try
            {
                PicTypeRemarkGroup picTypeRemarkGroups = obj;
                bool hasValidGroup = false; //用于判断是否存在有效分组(至少有一个分组存在有一张相片)
                for (int i = 0; i < picTypeRemarkGroups.picGroup.Length; i++)
                {
                    if (picTypeRemarkGroups.picGroup[i].pic.Length > 1)
                    {
                        hasValidGroup = true;
                        break;
                    }
                }
                if (hasValidGroup)
                {
                    using (Entities db = new Entities())
                    {
                        //存在有效分组，将数据保存至数据库

                        //写入证件类型表
                        TYPE type = db.TYPE.SingleOrDefault(a => a.TYPENAME == picTypeRemarkGroups.typeName);
                        if (type == null)
                        {
                            TYPE newType = new TYPE()
                            {
                                TYPENAME = picTypeRemarkGroups.typeName,
                                USERID = picTypeRemarkGroups.userId
                            };
                            db.TYPE.Add(newType);
                            db.SaveChanges();
                            type = db.TYPE.SingleOrDefault(a => a.TYPENAME == picTypeRemarkGroups.typeName);
                        }

                        //写入评语表
                        REMARK remark = db.REMARK.SingleOrDefault(a => a.REMARK1 == picTypeRemarkGroups.remark);
                        if (remark == null)
                        {
                            REMARK newRemark = new REMARK()
                            {
                                REMARK1 = picTypeRemarkGroups.remark,
                                USERID = picTypeRemarkGroups.userId
                            };
                            db.REMARK.Add(newRemark);
                            db.SaveChanges();
                            remark = db.REMARK.SingleOrDefault(a => a.REMARK1 == picTypeRemarkGroups.remark);
                        }

                        //写入证件类型评语关系表
                        if (type != null && remark != null)
                        {
                            db.TYPEREMARK.Add(new TYPEREMARK()
                            {
                                TYPEID = type.ID,
                                REMARKID = remark.ID,
                                USERID = picTypeRemarkGroups.userId
                            });
                            db.SaveChanges();
                        }

                        for (int i = 0; i < picTypeRemarkGroups.picGroup.Length; i++)
                        {
                            PicGroup tempGroup = picTypeRemarkGroups.picGroup[i];

                            if (picTypeRemarkGroups.picGroup[i].pic.Length > 1)
                            {
                                //写入分组表
                                REMARKGROUP rGroup = db.REMARKGROUP.SingleOrDefault(a => a.GROUPNAME == tempGroup.groupName && a.REMARKID == remark.ID);
                                
                                if (rGroup == null)
                                {
                                    REMARKGROUP newRGroup = new REMARKGROUP()
                                    {
                                        GROUPNAME = tempGroup.groupName,
                                        REMARKID = remark.ID,
                                        USERID = picTypeRemarkGroups.userId
                                    };
                                    db.REMARKGROUP.Add(newRGroup);
                                    db.SaveChanges();
                                    rGroup = db.REMARKGROUP.SingleOrDefault(a => a.GROUPNAME == tempGroup.groupName && a.REMARKID == remark.ID);
                                }

                                for (int j = 0; j < tempGroup.pic.Length - 1; j++)
                                {
                                    Pic tempPic = tempGroup.pic[j];
                                    int picId = Int32.Parse(tempPic.id);
                                    
                                    //如果要删除图片
                                    if (tempPic.del)
                                    {
                                        PIC delPic = db.PIC.Find(picId);
                                        db.PIC.Remove(delPic);
                                        db.SaveChanges();
                                    }
                                    
                                    //如果已存在图片证件类型评语分组关系记录,更新
                                    else if (!string.IsNullOrEmpty(tempPic.picTypeRemarkGroupId))
                                    {
                                        PICTYPEREMARKGROUP PTRG = db.PICTYPEREMARKGROUP.Find(Int32.Parse(tempPic.picTypeRemarkGroupId));
                                        if (PTRG != null)
                                        {
                                            PTRG.REMARKID = remark.ID;
                                            PTRG.TYPEID = type.ID;
                                            PTRG.REMARKGROUPID = rGroup.ID;
                                            PTRG.USERID = picTypeRemarkGroups.userId;
                                            using (Entities dbctx = new Entities())
                                            {
                                                dbctx.Entry(PTRG).State = EntityState.Modified;
                                                dbctx.SaveChanges();
                                            }
                                        }
                                    }                                        
                                    else
                                    {
                                        //写入图片证件类型评语分组关系表
                                        PICTYPEREMARKGROUP PTRG = new PICTYPEREMARKGROUP()
                                        {
                                            REMARKID = remark.ID,
                                            TYPEID = type.ID,
                                            REMARKGROUPID = rGroup.ID,
                                            PICID = picId,
                                            USERID = picTypeRemarkGroups.userId
                                        };                                        
                                        db.PICTYPEREMARKGROUP.Add(PTRG);
                                        db.SaveChanges();
                                    }
                                    
                                    if (!tempPic.del)
                                    {                                        
                                        //更新相片名称
                                        PIC pic = db.PIC.SingleOrDefault(a => (a.ID == picId) && (a.FILENAME != tempPic.fileName));
                                        if (pic != null)
                                        {
                                            pic.FILENAME = tempPic.fileName;
                                            using (Entities dbctx = new Entities())
                                            {
                                                dbctx.Entry(pic).State = EntityState.Modified;
                                                dbctx.SaveChanges();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    //return result;
                    return new JsonMessage();
                }
                else
                {
                    //不存在有效分组，返回错误信息
                    return new JsonMessage("没有有效的相片分组信息。请先上传相片！", "");
                }
            }
            catch (Exception ex)
            {
                return new JsonMessage("提交失败", ex.Message, ex.StackTrace);
            }            
        }

        // DELETE api/pictyperemarkgroups
        /// <summary>
        /// 删除相片分组信息(根据指定的证件类型和评语删除相片表和相片分组表记录)
        /// </summary>
        /// <returns></returns>
        public JsonMessage Delete()
        {
            try
            {
                int remarkId= int.Parse(HttpContext.Current.Request.QueryString["remarkid"]),
                    typeId = int.Parse(HttpContext.Current.Request.QueryString["typeid"]);
                string userId = HttpContext.Current.Request.QueryString["userid"];
                using (Entities db = new Entities())
                {
                    //获取证件类型和评语
                    TYPE type=db.TYPE.Find(typeId);
                    REMARK remark=db.REMARK.Find(remarkId);
                    if (type != null && remark != null)
                    {
                        //写操作日志
                        USER_LOG userLog = new USER_LOG()
                        {
                            USERID = userId,
                            ODATE = DateTime.Now,
                            CONTENT = "删除： 证件类型：\"" + remark.REMARK1 + "\"  评语：\"" + type.TYPENAME + "\""
                        };
                        db.USER_LOG.Add(userLog);
                        //删除证件类型评语关系表记录
                        TYPEREMARK tpRemark = db.TYPEREMARK.Single(a => a.TYPEID == typeId && a.REMARKID == remarkId);
                        if (tpRemark != null)
                        {
                            db.TYPEREMARK.Remove(tpRemark);
                        }
                        //删除相片记录
                        List<PICTYPEREMARKGROUP> PTRG = db.PICTYPEREMARKGROUP.Include("PIC").Where(a => a.TYPEID == typeId && a.REMARKID == remarkId).ToList();
                        foreach (PICTYPEREMARKGROUP ptrg in PTRG)
                        {
                            if (ptrg.PIC != null)
                            {
                                PICDATA pd = db.PICDATA.Single(a => a.ID == ptrg.PIC.ID);
                                if (pd != null)
                                {
                                    db.PICDATA.Remove(pd);
                                }
                                db.PIC.Remove(ptrg.PIC);
                            }
                        }
                        db.SaveChanges();
                    }
                }
                return new JsonMessage();
            }
            catch (Exception ex)
            {
                return new JsonMessage("删除失败", ex.Message, ex.StackTrace);
            }
        }
    }
}
